﻿using UnityEngine;
using System.Linq;
using System.Reflection;
using System.IO;
using System.Collections.Generic;
using HybridCLR;

namespace LitFramework
{
    public class GameState_Hybrid : IState
    {
        public StateMechine Master { get; set; }

        public async void OnEnter(params object[] values)
        {
            GameManager.Instance.InitState = "HybridCLR Init";
            GameManager.Instance.InitProgress = 0;

            bool useBytes = ProjectConfig.Config.useBytes;
            Assembly hotUpdateAss;
            if (useBytes)
            {
                var hotUpdateText = await AssetManager.Instance.LoadAsset<TextAsset>("HotUpdate.dll");
                hotUpdateAss = Assembly.Load(hotUpdateText.bytes);
                for (int i = 0; i < ProjectConfig.Config.aotDllList.Length; i++)
                {
                    var dll = ProjectConfig.Config.aotDllList[i];
                    var text = await AssetManager.Instance.LoadAsset<TextAsset>(dll);
                    var err = RuntimeApi.LoadMetadataForAOTAssembly(text.bytes, HomologousImageMode.SuperSet);
                    GameManager.Instance.InitProgress = i / (float)ProjectConfig.Config.aotDllList.Length;
                }
            }
            else
            {
                hotUpdateAss = System.AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == "HotUpdate");
            }

            GameManager.Instance.InitProgress = 1;
            var entranceType = hotUpdateAss.GetType("HBFramework.HotUpdate");
            var entranceMethod = entranceType.GetMethod("Start");
            entranceMethod.Invoke(null, null);
            Master.Stop();
        }

        public void OnUpdate()
        {

        }

        public void OnExit()
        {

        }
    }
}
